'use strict';
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
var pump = require('pump')
var http = require('http')
const { createBundleRenderer } = require('vue-server-renderer');
const indexHtml = fs.readFileSync(path.resolve(__dirname, '../public/common/index.html'), 'utf-8');
const template = fs.readFileSync(path.resolve(__dirname, '../public/common/index.ssr.html'), 'utf-8');
class PreViewController extends Controller {
  async index() {
    let id = this.ctx.query.id;
    if (id) {
      const page = await this.ctx.service.page.find(id);
      let ssrHtml = "";
      const getModuleHtml = (arr, ssrFlag) => {
        const baseUrl = 'http://localhost:7001/public'
        let strScript = ''
        arr.forEach((v,i) => {
          strScript +=  ssrFlag? "" : `<div id="module${i + 1}"></div>`;
          strScript +=`<script src="${baseUrl}/${v.module_name}/${v.edition}/daily/index.js"></script>`;
        })
        
        const strArr = arr.map(v => v.module_name);
        const propsArr = arr.map((v,i) => (JSON.stringify({
          ...JSON.parse(v.props),
          module_id: `module` + (i+1)
        })));
        strScript += `<script defer>
              let moduleArr= ${JSON.stringify(strArr)}; 
              let propsArr= ${JSON.stringify(propsArr)}; 
              for(var i = 0; i < moduleArr.length; i++){
                window[moduleArr[i]](JSON.parse(propsArr[i])).$mount("#module"+(i+1));
              }
          </script>`
        return strScript
      }
      if(String(page.open_ssr) === "true"){

        for (let i = 0; i < page.pageData.length; i ++) {
          const item = page.pageData[i];
          const serverBundle = JSON.parse(fs.readFileSync(path.resolve(__dirname, `../public/${item.module_name}/${item.edition}/daily/vue-ssr-server-bundle.json`), 'utf-8'));
          const clientManifest = require(path.resolve(__dirname, '../public/common/vue-ssr-client-manifest.json'));
          const renderer = createBundleRenderer(serverBundle, {
            runInNewContext: false,
            template: template,
            clientManifest: clientManifest
          });
          const ssrString = await renderer.renderToString({
            module_id: "module" + (i + 1),
            ...JSON.parse(item.props)
          })
          // 
          ssrHtml += ssrString.replace(/<script .*><\/script>/,"");
        }
      }
      
      let scriptStr = getModuleHtml(page.pageData, String(page.open_ssr) === "true");

      const bodyHtml = indexHtml.replace("{{模板}}", ssrHtml + scriptStr);
      this.ctx.type = 'html';
      this.ctx.body = bodyHtml;
    }
    else {
      this.ctx.body = '缺少必要参数';
    }
   
  }
}

module.exports = PreViewController;
